package com.ieng.ormosia.groups.exption;

import com.ieng.ormosia.common.utils.ActionR;
import com.ieng.ormosia.common.vo.ResponseData;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ResponseStatus(code = HttpStatus.BAD_REQUEST)
    @ExceptionHandler({BindException.class, ValidationException.class, MethodArgumentNotValidException.class})
    public ResponseData handleParameterVerifyException(Exception e){
        String message = null;
        if(e instanceof BindException){
            FieldError fieldError = ((BindException) e).getFieldError();
            if (fieldError != null) {
                message = fieldError.getDefaultMessage();
            }
        } else if(e instanceof MethodArgumentNotValidException){
            BindingResult result = ((MethodArgumentNotValidException) e).getBindingResult();
            FieldError fieldError = result.getFieldError();
            if (fieldError != null) {
                message = fieldError.getDefaultMessage();
            }
        } else if(e instanceof ConstraintViolationException){
            message = e.getMessage();
            if(message != null){
                int indexOf = message.lastIndexOf(":");
                if (indexOf >= 0) {
                    message = message.substring(indexOf + 1).trim();
                }
            }
        } else {
            message = "请求参数异常";
        }
        return ActionR.error(message);
    }



}
